package de.karlNet.sambamanager.ldapController;

import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapModel.FSMORoles;
import de.karlNet.sambamanager.ldapModel.LdapObject;

@Controller
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ConfigurationTree extends OriginalLdapTree {



	@SuppressWarnings("unchecked")
	public LdapObject findByServerRL(String dn) {
		@SuppressWarnings("rawtypes")
		List ldapObjects = getLdapTemplate().search("CN=Configuration," + this.getBaseDN(),
				"(serverReference=" + dn + "*)", SearchControls.SUBTREE_SCOPE,
				this.attributesMapper);
		List<LdapObject> ret = new ArrayList<LdapObject>(ldapObjects);
		return ret.get(0);
	}

	public List<FSMORoles> getFSMORoles(String dn) {
		final List<FSMORoles> fsmoRoles = new ArrayList<FSMORoles>();
		getLdapTemplate().search(this.getBaseDN(),
				"(fSMORoleOwner=" + dn + ")", SearchControls.SUBTREE_SCOPE,
				new AttributesMapper() {

					@Override
					public Object mapFromAttributes(Attributes attributes)
							throws NamingException {
						List<String> objectClasses = new ArrayList<String>();

						NamingEnumeration<?> objectclassEnum = attributes.get("objectclass")
								.getAll();
						while (objectclassEnum.hasMore()) {
							String objectClass = (String) objectclassEnum.next();
							objectClasses.add(objectClass);
						}
						for (String objectClass : objectClasses) {
							System.out.println(objectClass);
							if(objectClass.equals("rIDManager")) {
								fsmoRoles.add(FSMORoles.RID_MANAGER);
							} else if(objectClass.equals("infrastructureUpdate")) {
								fsmoRoles.add(FSMORoles.INFRASTRUCTURE_UPDATE);
							} else if(objectClass.equals("domainDNS")) {
								fsmoRoles.add(FSMORoles.DNS);
							} else if(objectClass.equals("dMD")) {
								fsmoRoles.add(FSMORoles.SCHEMA_MASTER);
							}
						}
						return null;
					}
			
		});
		return fsmoRoles;
	}
}
